package com.mini.grpc.serialization.json;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mini.grpc.serialization.Marshaller;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * JsonMarshaller实现了基于Jackson的JSON序列化和反序列化。
 *
 * @param <T> 要序列化和反序列化的对象类型
 */
public class JsonMarshaller<T> implements Marshaller<T> {
    
    private static final ObjectMapper MAPPER = new ObjectMapper();
    
    private final Class<T> clazz;
    
    /**
     * 创建一个新的JsonMarshaller
     *
     * @param clazz 要序列化和反序列化的对象类型
     */
    public JsonMarshaller(Class<T> clazz) {
        this.clazz = clazz;
    }
    
    @Override
    public InputStream stream(T value) {
        try {
            byte[] bytes = MAPPER.writeValueAsBytes(value);
            return new ByteArrayInputStream(bytes);
        } catch (IOException e) {
            throw new RuntimeException("Failed to serialize object to JSON", e);
        }
    }
    
    @Override
    public T parse(InputStream stream) {
        try {
            return MAPPER.readValue(stream, clazz);
        } catch (IOException e) {
            throw new RuntimeException("Failed to deserialize JSON to object", e);
        }
    }
    
    /**
     * 创建一个新的JsonMarshaller
     *
     * @param clazz 要序列化和反序列化的对象类型
     * @param <T> 对象类型
     * @return 新的JsonMarshaller
     */
    public static <T> JsonMarshaller<T> of(Class<T> clazz) {
        return new JsonMarshaller<>(clazz);
    }
} 